package com.twohand.admin.Service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.twohand.admin.Dto.BatchChangeMoneyDto;
import com.twohand.admin.Dto.GenUrlDto;
import com.twohand.admin.Dto.ShopInfoDto;
import com.twohand.admin.Dto.ShopListQueryDto;
import com.twohand.admin.Entity.Shop;
import com.twohand.admin.Entity.User;
import com.twohand.admin.Mapper.BillMapper;
import com.twohand.admin.Mapper.ShopMapper;
import com.twohand.admin.Service.ShopService;
import com.twohand.admin.Service.ShortLinkService;
import com.twohand.admin.Service.UserService;
import com.twohand.admin.Util.JwtUtil;
import com.twohand.admin.Util.PageResponse;
import com.twohand.admin.Vo.BillSearchResult;
import com.twohand.admin.Vo.GenUrlVo;
import com.twohand.admin.Vo.Order.OrderStatisVo;
import com.twohand.admin.Vo.SelectOptions;
import com.twohand.utils.Response.BaseException;
import com.twohand.utils.Response.Response;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.net.URLEncoder;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class ShopServiceImpl implements ShopService {
    @Autowired
    ShopMapper shopMapper;
    @Autowired
    ShortLinkService shortLinkService;
    @Autowired
    BillMapper billMapper;
    public Logger log = LoggerFactory.getLogger(ShopServiceImpl.class);
    @Value("${custom.webAddress}")
    String webAddress;
    @Value("${custom.copyText}")
    String copyText;
    @Value("${custom.managerUrl}")
    String managerUrl;
    @Autowired
    UserService userService;
    @Override
    public PageResponse<Shop> shopList(ShopListQueryDto shopListQueryDto) {
        User user = JwtUtil.getCurrentUser();
        log.info("currentUser:{}",user);
        User user1 = userService.getUserById(user.getId());
        log.info("findUser:{}",user1);
        PageHelper.startPage(shopListQueryDto.getPageNum(),shopListQueryDto.getPageSize());
        String shopName = shopListQueryDto.getShopName();
        Integer sid = shopListQueryDto.getSid();

        Integer userSid = user1.getSid();
        if(userSid!=0){
            sid = userSid;
            log.info("sid:{}",sid);
        }
        List<Shop> shopList = shopMapper.getList(shopName,sid,shopListQueryDto.getActiveDate(),shopListQueryDto.getPlatform(),shopListQueryDto.getStatus(),shopListQueryDto.getStartTime(),shopListQueryDto.getEndTime(),shopListQueryDto.getPriority(),shopListQueryDto.getRelevancy(),shopListQueryDto.getIsrelevancy());
        PageInfo<Shop> swipePageInfo = new PageInfo<>(shopList);
        return new PageResponse<Shop>(swipePageInfo,shopList);
    }

    @Override
    public Boolean addShop(Shop shop) {
        return shopMapper.insert(shop) > 0;
    }

    @Override
    public Boolean changShop(Shop shop) {

        return shopMapper.updateById(shop) > 0;
    }

    @Override
    public Boolean delShop(Integer id) {
        return shopMapper.deleteById(id) > 0;
    }

    @Override
    public List<SelectOptions> getOptions() {
        return shopMapper.getOptions();
    }

    @Override
    public List<SelectOptions> getShopNameOption() {
        return shopMapper.getShopNameOption();
    }

    @Override
    public Shop selectShopByNameAndPlatform(String shopName,Integer platform) {
        LambdaQueryWrapper<Shop> shopLambdaQueryWrapper = new LambdaQueryWrapper<>();

        shopLambdaQueryWrapper.eq(Shop::getShopName,shopName)
                .eq(Shop::getPlatform,platform);
        Shop shop = shopMapper.selectOne(shopLambdaQueryWrapper);
        return shop;
    }

    @Override
    public Object checkAndAddShop(List<ShopInfoDto> shopInfos) {
        Integer success = 0;
        for (ShopInfoDto shopInfo:shopInfos) {
            //根据店名和类型查询是否存在记录
            String shopName = shopInfo.getShopName();
            Integer platform = shopInfo.getPlatform();
            Shop shop = selectShopByNameAndPlatform(shopName,platform);
            if(shop == null){
                shop = new Shop();
                shop.setShopName(shopName);
                shop.setPlatform(platform);
                Integer res = shopMapper.insert(shop);
                success+=res;
                log.info("店名:"+shopName+"platform:"+platform+"不存在，创建结果:"+res);
            }
        }
        return new Response(203,"成功添加店铺"+success+"个",null);
    }

    /**
     *   根据店铺名称获取店铺信息
     * @param shopName
     * @return
     */
    @Override
    public Shop selectShopByName(String shopName) {
        LambdaQueryWrapper<Shop> shopLambdaQueryWrapper = new LambdaQueryWrapper<>();
        shopLambdaQueryWrapper.eq(Shop::getShopName,shopName);
        List<Shop> shops = shopMapper.selectList(shopLambdaQueryWrapper);
        if (shops.isEmpty()) {
            return null;
        } else if (shops.size() > 1) {
            // 记录日志或抛出业务异常
            log.warn("发现重复店铺名称: {}, 共 {} 条记录", shopName, shops.size());
            return shops.get(0); // 或者抛出异常 throw new BusinessException("存在重复店铺");
        }
        return shops.get(0);
    }

    @Override
    public Shop selectShopById(Integer id) {
        LambdaQueryWrapper<Shop> shopLambdaQueryWrapper = new LambdaQueryWrapper<>();
        shopLambdaQueryWrapper.eq(Shop::getId,id);
        Shop shop = shopMapper.selectOne(shopLambdaQueryWrapper);
        return shop;
    }

    /**
     *   根据店铺名称获取连接
     * @param genUrlDto
     * @return
     * @throws ParseException
     */
    @Override
    public GenUrlVo getUrlNew(GenUrlDto genUrlDto) throws ParseException {
        String shopName = String.valueOf(genUrlDto.getId());
        Shop shopInfo = this.selectShopById(genUrlDto.getId());
        shopMapper.updateUrlIsGenByRelevancy(shopInfo.getRelevancy());


//        String activeDate = genUrlDto.getActiveDate();
        log.info("接收的参数---getUrlNew");
        Integer orderNum = 0;
        BigDecimal orderMoney = BigDecimal.ZERO;
        String d = "";
        List<String> dateList = new ArrayList<>();
        dateList.add("");
        dateList.add("");
        List<String> platformType = new ArrayList<>();
//        dateList.set(0,"");
//        dateList.set(1,"");
        List<BillSearchResult> billSearchResult = billMapper.getBillDetailListByRelevancy(shopInfo.getRelevancy(),null,0,null);
        if(billSearchResult.size()==0){
            throw new BaseException(500,"当前店铺暂无账单");
        }
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

        List<String> shopList = new ArrayList<>();  // 店铺集合
        for (BillSearchResult bill:billSearchResult) {
            orderNum += bill.getOrderNum();
//            orderMoney += bill.getOrderMoney();
            orderMoney = orderMoney.add(new BigDecimal(Float.toString(bill.getOrderMoney())));
            String activeDate = bill.getActiveDate();
            if(dateList.get(0).equals("")){
                dateList.set(0,activeDate);
            }else {
                //获取存储的时间
                Date date1 = sdf.parse(dateList.get(0));
                Date date2 = sdf.parse(activeDate);
                if(date2.before(date1)){
                    dateList.set(0,sdf.format(date2));
                }
            }
            if(dateList.get(1).equals("")){
                dateList.set(1,activeDate);
            }else{
                Date date3 = sdf.parse(dateList.get(1));
                Date date4 = sdf.parse(activeDate);
                if(date4.after(date3)){
                    dateList.set(0,sdf.format(date3));
                }
            }
            //添加账单平台类型
            String platform = bill.getPlatform();
            if(!platformType.contains(platform)){
                platformType.add(platform);
            }

            //添加账单平台类型
            String shopname = bill.getShopName();
            if(!shopList.contains(platform +":"+ shopname)){
                shopList.add(platform +":"+ shopname);
            }
        }
//        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        SimpleDateFormat sd1 = new SimpleDateFormat("MM月dd日");
        SimpleDateFormat sd2 = new SimpleDateFormat("dd日");
        SimpleDateFormat sd3 = new SimpleDateFormat("yyyy年MM月dd日");
        String dateString = "";
        String stringdate1 = dateList.get(0);
        String stringdate2 = dateList.get(1);
        if(stringdate1.equals(stringdate2)){
            Date date = sdf.parse(stringdate1);
            dateString = sd1.format(date);
        }else{
            Date date1 = sdf.parse(stringdate1);
            Date date2 = sdf.parse(stringdate2);
            if(date1.getYear() == date2.getYear()){
                if(date1.getMonth() == date2.getMonth()){
                    dateString = sd1.format(date1) + "~" + sd2.format(date2);
                }else{
                    dateString = sd1.format(date1) + "~" + sd1.format(date2);
                }
            }else{
                dateString = sd3.format(date1) + "~" + sd3.format(date2);
            }
        }
        log.info("时间信息：{}；{}；{}；{}",dateList,stringdate1,stringdate2,dateString);
//        Date date = simpleDateFormat.parse(d);
//        String dateString = sd1.format(date);
        String address = managerUrl + shortLinkService.generateShortLink(webAddress.replace("{shopName}", URLEncoder.encode(shopName)));
        log.info("替换后的链接:"+address);
        log.info("账单类型:{}",platformType);
        StringBuilder shop = new StringBuilder("");


        // 获取新的店铺名称
       // List<SelectOptions> shopList = shopMapper.selectShopByNameList(shopInfo.getRelevancy());
        shopList.stream().forEach(p->{
            shop.append("\n"+p);
        });
        String text = copyText
                .replace("{webAddress}",address)
                .replace("{date}",dateString)
                .replace("{orderNum}",orderNum+"")
                .replace("{orderMoney}",orderMoney.toString())
                .replace("{shopName}",shop.toString());
        log.info("替换后的文本:"+text);

        GenUrlVo genUrlVo = new GenUrlVo();
        genUrlVo.setText(text);
        genUrlVo.setUrl(address);
        return genUrlVo;
    }
    @Override
    public GenUrlVo getUrl(GenUrlDto genUrlDto) throws ParseException {
        String shopName = String.valueOf(genUrlDto.getId());
        shopMapper.updateUrlIsGen(null,genUrlDto.getId());
        Shop shopInfo = this.selectShopById(genUrlDto.getId());
//        String activeDate = genUrlDto.getActiveDate();
        log.info("接收的参数");
        Integer orderNum = 0;
        BigDecimal orderMoney = BigDecimal.ZERO;
        String d = "";
        List<String> dateList = new ArrayList<>();
        dateList.add("");
        dateList.add("");
        List<String> platformType = new ArrayList<>();
//        dateList.set(0,"");
//        dateList.set(1,"");
       // List<BillSearchResult> billSearchResult = billMapper.getBillDetailList(shopName,null,0,null);
        List<BillSearchResult> billSearchResult = billMapper.getBillDetailListById(genUrlDto.getId(),null,0,null);
        if(billSearchResult.size()==0){
            throw new BaseException(500,"当前店铺暂无账单");
        }
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

        for (BillSearchResult bill:billSearchResult) {
            orderNum += bill.getOrderNum();
//            orderMoney += bill.getOrderMoney();
            orderMoney = orderMoney.add(new BigDecimal(Float.toString(bill.getOrderMoney())));
            String activeDate = bill.getActiveDate();
            if(dateList.get(0).equals("")){
                dateList.set(0,activeDate);
            }else {
                //获取存储的时间
                Date date1 = sdf.parse(dateList.get(0));
                Date date2 = sdf.parse(activeDate);
                if(date2.before(date1)){
                    dateList.set(0,sdf.format(date2));
                }
            }
            if(dateList.get(1).equals("")){
                dateList.set(1,activeDate);
            }else{
                Date date3 = sdf.parse(dateList.get(1));
                Date date4 = sdf.parse(activeDate);
                if(date4.after(date3)){
                    dateList.set(0,sdf.format(date3));
                }
            }
            //添加账单平台类型
            String platform = bill.getPlatform();
            if(!platformType.contains(platform)){
                platformType.add(platform);
            }
        }
//        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        SimpleDateFormat sd1 = new SimpleDateFormat("MM月dd日");
        SimpleDateFormat sd2 = new SimpleDateFormat("dd日");
        SimpleDateFormat sd3 = new SimpleDateFormat("yyyy年MM月dd日");
        String dateString = "";
        String stringdate1 = dateList.get(0);
        String stringdate2 = dateList.get(1);
        if(stringdate1.equals(stringdate2)){
            Date date = sdf.parse(stringdate1);
            dateString = sd1.format(date);
        }else{
            Date date1 = sdf.parse(stringdate1);
            Date date2 = sdf.parse(stringdate2);
            if(date1.getYear() == date2.getYear()){
                if(date1.getMonth() == date2.getMonth()){
                    dateString = sd1.format(date1) + "~" + sd2.format(date2);
                }else{
                    dateString = sd1.format(date1) + "~" + sd1.format(date2);
                }
            }else{
                dateString = sd3.format(date1) + "~" + sd3.format(date2);
            }
        }
        log.info("时间信息：{}；{}；{}；{}",dateList,stringdate1,stringdate2,dateString);
//        Date date = simpleDateFormat.parse(d);
//        String dateString = sd1.format(date);
        String address = managerUrl + shortLinkService.generateShortLink(webAddress.replace("{shopName}", URLEncoder.encode(shopName)));
        log.info("替换后的链接:"+address);
        log.info("账单类型:{}",platformType);
        StringBuilder shop = new StringBuilder("");
        platformType.stream().forEach(p->{
            shop.append("\n"+p+":"+shopInfo.getShopName());
        });
        String text = copyText
                .replace("{webAddress}",address)
                .replace("{date}",dateString)
                .replace("{orderNum}",orderNum+"")
                .replace("{orderMoney}",orderMoney.toString())
                .replace("{shopName}",shop.toString());
        log.info("替换后的文本:"+text);

        GenUrlVo genUrlVo = new GenUrlVo();
        genUrlVo.setText(text);
        genUrlVo.setUrl(address);
        return genUrlVo;
    }

    @Override
    public void updateUrlIsGen(String shopName, Integer shopId) {
        shopMapper.updateUrlIsGen(shopName,shopId);
    }

    @Override
    public void updateUrlIsNotGen(String shopName, Integer shopId) {
        shopMapper.updateUrlIsNotGen(shopName,shopId);
    }

    @Override
    public OrderStatisVo OrderStatis(ShopListQueryDto shopListQueryDto) {
        Integer sid = shopListQueryDto.getSid();
        User user = JwtUtil.getCurrentUser();
        User user1 = userService.getUserById(user.getId());
        Integer userSid = user1.getSid();
        if(userSid!=0){
            sid = userSid;
        }
        OrderStatisVo statisVo = shopMapper.OrderStatis(shopListQueryDto.getShopName(),
                sid,shopListQueryDto.getActiveDate(),shopListQueryDto.getPlatform(),shopListQueryDto.getStatus(),shopListQueryDto.getStartTime(),shopListQueryDto.getEndTime(),shopListQueryDto.getPriority(),shopListQueryDto.getRelevancy(),shopListQueryDto.getIsrelevancy());
        if(statisVo==null)return new OrderStatisVo();
        return statisVo;

    }

    @Override
    public List<Shop> getSalesShop(Integer sid, String shopName, Integer platform) {
        LambdaQueryWrapper<Shop> shopLambdaQueryWrapper = new LambdaQueryWrapper<>();
        if(sid!=null&&sid!=0){
            shopLambdaQueryWrapper.eq(Shop::getSid,sid);
        }
        if(StringUtils.isNoneEmpty(shopName)){
            shopLambdaQueryWrapper.like(Shop::getShopName,shopName);
        }
        if(platform !=null){
            shopLambdaQueryWrapper.eq(Shop::getPlatform,platform);
        }
        return shopMapper.selectList(shopLambdaQueryWrapper);
    }

    @Override
    public List<String> groupByActiveDate(ShopListQueryDto shopListQueryDto) {
        User user = JwtUtil.getCurrentUser();
        User user1 = userService.getUserById(user.getId());
        Integer sid = user1.getSid();
        Integer qsid = shopListQueryDto.getSid();
        String shopName = shopListQueryDto.getShopName();
        Integer platform = shopListQueryDto.getPlatform();

        if(qsid!=null&&sid==0){
            log.info("shopListQueryDto sid:{}",qsid);
            sid = qsid;
        }
        List<Integer> shopIds = null;
//        if(sid!=0){
        List<Shop> shopList = getSalesShop(sid,shopName,platform);
        shopIds = shopList.stream().map(Shop::getId).collect(Collectors.toList());
        if(shopIds.size()==0){
            shopIds = null;
        }
//        }
        Integer status = shopListQueryDto.getStatus();

        log.info("shopIds:{}",shopIds);
        return billMapper.groupActiveDate(shopIds,status);
    }

    @Override
    public Shop getShopById(Integer shopId) {
        return shopMapper.selectById(shopId);
    }


    @Override
    public Boolean priorityShop(Integer id) {
        return shopMapper.priorityShop(id) ;
    }


    @Override
    public Boolean batchChangeRelevancy(BatchChangeMoneyDto batchChangeMoneyDto) {
        List<String> ids = batchChangeMoneyDto.getIds();
        if(ids.size()==0){
            throw new BaseException(500,"未勾选需要修改的数据！");
        }
        return shopMapper.batchChangeRelevancy(ids,batchChangeMoneyDto.getRelevancy()) > 0;
    }


}
